<?php

namespace App\Http\Controllers\Api\V1;


use App\Extend\OpenSearch\CloudsearchClient;
use App\Extend\OpenSearch\CloudsearchSearch;
use App\Extend\OpenSearch\CloudsearchSuggest;
use App\Helpers\FileTool;
use App\Http\Resources\AdCollection;
use App\Http\Resources\CategoryCollection;
use App\Http\Resources\DocCollection;
use App\Http\Resources\UserListenedCollection;
use App\Models\Ad;
use App\Models\AdPositionId;
use App\Models\Category;
use App\Models\Doc;
use App\Models\DocPage;
use App\Models\UserListened;
use Illuminate\Http\Request;

class IndexController extends BaseController
{

    public function index(Request $request)
    {
        $page = $request->input("page", 1);
        if ($page == 1) {
            //幻灯片
            $banner_ap = AdPositionId::getAdPositionIdByCode('index-banner');
            $banner = Ad::query()->with(['ad_position'])->where('ad_position_id', $banner_ap->id)->where('state', 1)->orderByDesc('order')->limit(8)->get();
            $data['banner'] = AdCollection::make($banner);
            //宫格导航
            $grid_ap = AdPositionId::getAdPositionIdByCode('index-grid-menu');
            $grid_menu = Ad::query()->with(['ad_position'])->where('ad_position_id', $grid_ap->id)->where('state', 1)->orderByDesc('order')->limit(5)->get();
            $data['grid_menu'] = AdCollection::make($grid_menu);
            //推荐内容
            $hot = \Cache::remember('index-hots-', 0, function () {
                return Doc::query()->with([
                    'category',
                    'user',
                    'last_update'
                ])->where('hot', '>', 0)->where('approved', 1)->orderByDesc('hot')->limit(8)->get();
            });
            $data['hot'] = DocCollection::make($hot)->hide(['page_count', 'buy_info', 'comment_count', 'subscribe_count'])
                ->relate(['user' => ['show', 'name']]);
            //分类下推荐内容
            $class_rec = \Cache::remember('index-class_recs-', 0, function () {
                return Category::query()->with([
                    'docs' => function ($query) {
                        $query->where('approved', 1)->where('home', '>', 0)->limit(8)->orderByDesc('home');
                    },
                    'docs.category',
                    'docs.listened' => function ($query) {
                        $query->groupBy("user_id", "parent_id");
                    },
                    'docs.tags',
                    'docs.user'
                ])->where('home', '>', 0)->orderByDesc('home')->get();
            });
            $data['class_rec'] = CategoryCollection::make($class_rec)->type('home');
        }
        $data['home_list'] = DocCollection::make($this->get_home_list())
            ->hide(['tags', 'page_count', 'buy_info', 'comment_count', 'subscribe_count'])
            ->relate(['user' => ['show', 'name']]);
        return $this->success($data);

    }

    protected function get_home_list()
    {
        $doc = Doc::query()->where('approved', 1)->orderByDesc('moderated_at');
        $doc->withCount([
        ]);
        $doc->with([
            'listened' => function ($query) {
                $query->groupBy("user_id", "parent_id");
            },
            'user',
            'pages',
            'category'
        ]);
        $page = $doc->paginate();
        return $page;
    }


    public function user_listened()
    {
        $user = $this->getUser();


        $wl = UserListened::query()->selectRaw('max(updated_at) as ua')->groupBy('parent_id')->where('user_id', $user->id)->get(['ua']);


        $user_listened = UserListened::query()->where('item_type', DocPage::class)->where('user_id', $user->id)->whereIn('updated_at', $wl)->orderByDesc('updated_at');

        $user_listened->with([
            'item',
            'item.doc',
            'item.doc.listened' => function ($query) use ($user) {
                $query->where("user_id", $user->id);
            },
            'item.doc.pages',
            'item.doc.category',
        ]);
        $page = $user_listened->paginate();
        $data = UserListenedCollection::make($page)->relate([
            'doc_page' => ['show', 'id', 'title', 'updated_format', 'doc', 'link'],
            'doc' => ['show', 'id', 'cover', 'title', 'page_count', 'category_name', 'listened_count']
        ]);

        return $this->success($data);

    }

    public function search(Request $request)
    {
        error_reporting(0);
        $key = $request->input("key");
        $page = $request->input("page");
        $rows = 20;
        $start = ($page - 1) * 20;
        $access_key = config('scout.opensearch.accessKeyID');
        $secret = config('scout.opensearch.accessKeySecret');
        $host = config('scout.opensearch.host');//根据自己的应用区域选择API
        $key_type = "aliyun";  //固定值，不必修改
        $opts = array('host' => $host);
        $app_name = config('scout.opensearch.appName');
        $client = new CloudsearchClient($access_key, $secret, $opts, $key_type);
        // 实例化一个搜索类
        $search_obj = new CloudsearchSearch($client);
        // 指定一个应用用于搜索
        $search_obj->addIndex($app_name);
        // 指定搜索关键词
        $search_obj->setQueryString("content:" . $key);
        // 指定返回的搜索结果的格式为json
        $search_obj->setFormat("json");
        $search_obj->setStartHit($start);
        $search_obj->setHits($rows);
        // 执行搜索，获取搜索结果
        $json = $search_obj->search();
        // 将json类型字符串解码
        $result_data = json_decode($json, true);
        $result = [];
        if (strtolower($result_data['status']) === 'ok') {
            $result = $result_data['result'];
            foreach ($result['items'] as $k => $v) {
                $result['items'][$k]['id'] = hashid_encode($v['id']);
                $result['items'][$k]['doc_id'] = hashid_encode($v['doc_id']);
                $result['items'][$k]['link'] = urlencode(config('wx.web_host') . 'doc-page?id=' . hashid_encode($v['id']));
                $result['items'][$k]['title'] = $this->set_key($v['title']);
                $result['items'][$k]['content'] = $this->set_key($v['content']);
                $result['items'][$k]['cover'] = FileTool::thumb($v['cover'], FileTool::getImageView(120, 120));
            }
        }

        $data['data'] = [
            'items' => $result['items'],
            'total' => $result['total'],
            'searchtime' => $result['searchtime'],
        ];
        $data['meta'] = [
            'current_page' => (int)$page,
            'last_page' => (int)($result['total'] / $rows),
            'per_page' => (int)$rows,
            'total' => (int)$result['total'],
        ];
        return $this->success($data);
    }

    public function title_tip(Request $request)
    {
        error_reporting(0);
        $key = $request->input("key");
        $access_key = config('scout.opensearch.accessKeyID');
        $secret = config('scout.opensearch.accessKeySecret');
        $host = config('scout.opensearch.host');//根据自己的应用区域选择API
        $key_type = "aliyun";  //固定值，不必修改
        $opts = array('host' => $host);
        $app_name = config('scout.opensearch.appName');
        $client = new CloudsearchClient($access_key, $secret, $opts, $key_type);
        $suggest = new CloudsearchSuggest($client);
        $suggest->setIndexName($app_name);
        $suggest->setSuggestName("title");
        $suggest->setHits(8);
        $suggest->setQuery($key);
        $result = json_decode($suggest->search(), true);
        return $this->success($result);
    }


    protected function set_key($str)
    {
        $str = str_replace("<span>", "<span style='color: #ff0000'>", $str);
        return $str;
    }

}